package top.whysu.rongcloud.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import top.whysu.rongcloud.constant.CodeConstant;
import top.whysu.rongcloud.dto.file.FileDTO;
import top.whysu.rongcloud.dto.http.Response;
import top.whysu.rongcloud.fastdfs.FastDFSClientWrapper;
import top.whysu.rongcloud.util.ResponseUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 文件上传
 */
@Controller
public class FileController {

    @Resource
    private FastDFSClientWrapper dfsClient;

    @Value("${erongcloud.fileRoot}")
    private String fileRoot;

    @ResponseBody
    @PostMapping("/uploadFile")
    public Response upload(@RequestParam(name = "uploadFile") List<MultipartFile> fileList, HttpServletRequest request) throws IOException {
        // 上传文件
        String filePath = dfsClient.uploadFile(fileList.get(0), "jpg");
        if (StringUtils.isNotBlank(filePath)) {
            FileDTO fileDTO = new FileDTO();
            fileDTO.setUrl(fileRoot + File.separator + filePath);
            return ResponseUtil.getSuccessResponse(fileDTO);
        } else {
            return ResponseUtil.getResponse(CodeConstant.Common.FILE_UPLOAD_FAIL, "图片上传失败！", null);
        }
    }

    /**
     * 移除FastDFS服务器中的文件
     */
    @ResponseBody
    @PostMapping("/deleteFile")
    public Response deleteFile(@RequestParam(name = "url") String url) throws IOException {
        dfsClient.deleteFile(url);
        return ResponseUtil.getSuccessResponse();
    }

}
